package controllers

import (
	"Article-Manage/models"
	"encoding/base64"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UserController struct {
	BaseController
}

func (c *UserController) GetRegister() {
	c.TplName = "register.html"
}

func (c *UserController) PostRegister() {
	c.TplName = "register.html"

	userName := c.GetString("userName")
	pwd := c.GetString("password")

	if userName == "" || pwd == "" {
		c.Data["errmsg"] = "注册数据不完整，请重新注册"
		beego.Info("注册数据不完整，请重新注册")
		return
	}
	user := models.User{
		Name:   userName,
		Passwd: pwd,
	}
	orm.NewOrm().Insert(&user)
	c.Redirect("/login", 302)
}

func (c *UserController) GetLogin() {
	userName := c.Ctx.GetCookie("userName")
	temp,_:=base64.StdEncoding.DecodeString(userName)
	if userName==""{
		c.Data["userName"] = ""
		c.Data["checked"] = ""
	} else {
		c.Data["userName"] = string(temp)
		c.Data["checked"] = "checked"
	}
	beego.Info(userName)
	c.TplName = "login.html"
}

func (c *UserController) PostLogin() {
	c.TplName = "login.html"

	userName := c.GetString("userName")
	pwd := c.GetString("password")
	remember := c.GetString("remember")

	if userName == "" || pwd == "" {
		c.Data["errmsg"] = "登录数据不完整，请重新登录"
		beego.Info("登录数据不完整，请重新登录")
		return
	}
	user := models.User{
		Name: userName,
	}
	orm.NewOrm().Read(&user, "Name")
	if user.Passwd != pwd {
		c.Data["errmsg"] = "用户名或者密码错误"
		return
	}
	if remember == "on" {
		temp:=base64.StdEncoding.EncodeToString([]byte(userName))
		c.Ctx.SetCookie("userName",temp,20000)
	} else {
		c.Ctx.SetCookie("userName",userName,-1)
	}
	c.SetSession("userName",userName)

	c.Redirect("/articles", 302)
}

func (c *UserController) Logout() {
	c.DelSession("userName")
	c.Redirect("/login",302)
}
